﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Management;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using System.Data.SqlClient;
using Microsoft.ConfigurationManagement.ManagementProvider;
using Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine;

namespace AppImporter
{
    public partial class AppfolderBrowse : Form
    {
        private System.Collections.ArrayList arrApplicationFolders;
        string subfoldervalue = "";
        public object SCCMWQLConnection;
        public XmlDocument guiConfig = new XmlDocument();

        static void AppfolderBrowse_Main(string[] args)
        {

            //string computer = guiConfig.SelectSingleNode("/AppImporter/SCCMServer").InnerText;
            //string userName = "";
            //string password = "";

            //WMIConnectClass WMIConnect = new WMIConnectClass();
            //WqlConnectionManager WMIConnection = WMIConnect.Connect(computer, userName, password);
            //this.SCCMWQLConnection = this.Connect(Properties.Settings.Default.SCCM_Server);

        }

        public AppfolderBrowse()
        {
            guiConfig.Load(@".\Settings.xml");
            arrApplicationFolders = new System.Collections.ArrayList();
            InitializeComponent();
        }

        public event ValueUpdatedEventHandler ValueUpdated;

        #region Functions


        private string PkgfldDetails(string ContainerNodeID)
        {
            System.Collections.ArrayList aResult = new System.Collections.ArrayList();

            ManagementObjectSearcher searcher = new ManagementObjectSearcher("\\\\" + guiConfig.SelectSingleNode("/AppImporter/SCCMServer").InnerText + "\\root\\SMS\\site_" + guiConfig.SelectSingleNode("/AppImporter/SCCMSiteCode").InnerText, "SELECT Name,ContainerNodeID,ParentContainerNodeID FROM SMS_ObjectContainerNode WHERE SearchFolder = 0 AND ObjectType = 6000 AND ContainerNodeID = " + ContainerNodeID);
            string ContainerName = null;

            foreach (ManagementObject qresult in searcher.Get())
            {
                //MessageBox.Show(qresult["Name"].ToString());
                ContainerName = qresult["Name"].ToString();
            }

            //managementScope = null;
            //objectQuery = null;
            //managementObject = null;
            return ContainerName.ToString();

            //return PkgfldDetails(CollectionID, "*");
        }

        private String[] SubPgmFld(string ContainerNodeID)
        {

            try
            {
                System.Collections.ArrayList aResult = new System.Collections.ArrayList();

                ManagementObjectSearcher searcher = new ManagementObjectSearcher("\\\\" + guiConfig.SelectSingleNode("/AppImporter/SCCMServer").InnerText + "\\root\\SMS\\site_" + guiConfig.SelectSingleNode("/AppImporter/SCCMSiteCode").InnerText, "SELECT Name,ContainerNodeID,ParentContainerNodeID FROM SMS_ObjectContainerNode WHERE SearchFolder = 0 AND ObjectType = 6000 AND ParentContainerNodeID = " + ContainerNodeID);

                foreach (ManagementObject qresult in searcher.Get())
                {
                    //MessageBox.Show(qresult["ContainerNodeID"].ToString());
                    aResult.Add(qresult["ContainerNodeID"].ToString());
                }

                return aResult.ToArray(typeof(string)) as string[];
            }
            catch (ManagementException e)
            {
                MessageBox.Show("An error occurred while querying for WMI data: " + e.Message + e.ErrorInformation);
                return null;
            }

        }



        #endregion

        private void AppfolderBrowse_Load(object sender, EventArgs e)
        {
            this.SCCMWQLConnection = this.Connect(guiConfig.SelectSingleNode("/AppImporter/SCCMServer").InnerText);

            string[] sCols = SubPgmFld("0");
            foreach (string sCol in sCols)
            {
                TreeNode tNode = new TreeNode(PkgfldDetails(sCol).ToString());
                tNode.Tag = sCol;
                tNode.Name = sCol;
                tNode.Nodes.Add("");
                treeView1.Nodes[0].Nodes.Add(tNode);
            }

            treeView1.Sort();

        }

        private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            if (e.Node.Nodes.Count == 1 && e.Node.Nodes[0].Text == "")
            {
                if (e.Node.Nodes[0].Text == "")
                {
                    e.Node.Nodes.Clear();
                }

                string sRoot = e.Node.Tag.ToString();
                string[] sCols = SubPgmFld(sRoot);
                foreach (string sCol in sCols)
                {
                    TreeNode tNode = new TreeNode(PkgfldDetails(sCol).ToString());
                    tNode.Tag = sCol;
                    tNode.Name = sCol;
                    tNode.Nodes.Add("");
                    e.Node.Nodes.Add(tNode);
                }
            }


        }



        private void bt_collection_select_Click(object sender, EventArgs e)
        {
            //MessageBox.Show(treeView1.SelectedNode.Text.ToString() + Environment.NewLine + treeView1.SelectedNode.Name.ToString());
            string newValue = treeView1.SelectedNode.Name.ToString() + ';' + treeView1.SelectedNode.Text.ToString();
            ValueUpdatedEventArgs valueArgs = new ValueUpdatedEventArgs(newValue);
            ValueUpdated(this, valueArgs);
            Dispose();
        }

        private void bt_newFolder_Click(object sender, EventArgs e) //TreeViewCancelEventArgs e
        {
            //Int32 objecttype = 2;
            if (InputBox("New Subfolder name", "Enter the name for the new sub folder:", ref subfoldervalue) == DialogResult.OK)
            {
                //MessageBox.Show(subfoldervalue + " " + treeView1.SelectedNode.Name);
                CreateConsoleFolder((WqlConnectionManager)SCCMWQLConnection, subfoldervalue, 6000, Convert.ToInt32(treeView1.SelectedNode.Name.ToString()));

                // # Reload treeview after the new node is added.
                treeView1.Nodes.Clear();
                treeView1.Nodes.Add("Applications");

                string[] sCols = SubPgmFld("0");
                foreach (string sCol in sCols)
                {
                    TreeNode tNode = new TreeNode(PkgfldDetails(sCol).ToString());
                    tNode.Tag = sCol;
                    tNode.Name = sCol;
                    tNode.Nodes.Add("");
                    treeView1.Nodes[0].Nodes.Add(tNode);
                }

                treeView1.Sort();

                //Clear the inputvalue
                subfoldervalue = "";

            }
        }

        public void CreateConsoleFolder(WqlConnectionManager connection, string name, Int32 objectType, Int32 parentNodeID)
        {
            try
            {
                IResultObject folder = connection.CreateInstance("SMS_ObjectContainerNode");
                folder["Name"].StringValue = name;
                folder["ObjectType"].IntegerValue = objectType;
                folder["ParentContainerNodeID"].IntegerValue = parentNodeID;

                folder.Put();
            }
            catch (SmsException e)
            {
                Console.WriteLine("Failed to create folder. Error: " + e.Message);
                throw;
            }
        }



        public WqlConnectionManager Connect(string serverName)
        {
            try
            {
                SmsNamedValuesDictionary namedValues = new SmsNamedValuesDictionary();
                WqlConnectionManager connection = new WqlConnectionManager(namedValues);
                if (System.Net.Dns.GetHostName().ToUpper() == serverName.ToUpper())
                {
                    connection.Connect(serverName);
                }
                else
                {
                    connection.Connect(serverName);
                }
                return connection;
            }
            catch (SmsException ex)
            {
                Console.WriteLine("Failed to Connect. Error: " + ex.Message);
                return null;
            }
            catch (UnauthorizedAccessException ex)
            {
                Console.WriteLine("Failed to authenticate. Error:" + ex.Message);
                return null;
            }
        }

        public static DialogResult InputBox(string title, string promptText, ref string value)
        {
            Form form = new Form();
            Label label = new Label();
            TextBox textBox = new TextBox();
            Button buttonOk = new Button();
            Button buttonCancel = new Button();

            form.Text = title;
            label.Text = promptText;
            textBox.Text = value;

            buttonOk.Text = "OK";
            buttonCancel.Text = "Cancel";
            buttonOk.DialogResult = DialogResult.OK;
            buttonCancel.DialogResult = DialogResult.Cancel;

            label.SetBounds(9, 20, 372, 13);
            textBox.SetBounds(12, 36, 372, 20);
            buttonOk.SetBounds(228, 72, 75, 23);
            buttonCancel.SetBounds(309, 72, 75, 23);

            label.AutoSize = true;
            textBox.Anchor = textBox.Anchor | AnchorStyles.Right;
            buttonOk.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;

            form.ClientSize = new Size(396, 107);
            form.Controls.AddRange(new Control[] { label, textBox, buttonOk, buttonCancel });
            form.ClientSize = new Size(Math.Max(300, label.Right + 10), form.ClientSize.Height);
            form.FormBorderStyle = FormBorderStyle.FixedDialog;
            form.StartPosition = FormStartPosition.CenterScreen;
            form.MinimizeBox = false;
            form.MaximizeBox = false;
            form.AcceptButton = buttonOk;
            form.CancelButton = buttonCancel;

            DialogResult dialogResult = form.ShowDialog();
            value = textBox.Text;
            return dialogResult;
        }


    }

}
